#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <windows.h>
#include "ni488.h"

#define ARRAYSIZE 100            // Size of read buffer
int Dev; // Device handle
char ReadBuffer[ARRAYSIZE + 1]; // Read data buffer
char ErrorMnemonic[21][5] = { "EDVR", "ECIC", "ENOL", "EADR", "EARG", "ESAC",
		"EABO", "ENEB", "EDMA", "", "EOIP", "ECAP", "EFSO", "", "EBUS", "ESTB",
		"ESRQ", "", "", "", "ETAB" };
void GPIBCleanup(int Dev, char* ErrorMsg);

int main(void) {
	Dev = ibfind("GPIB0"); // 寻找 GPIB 接口卡
	if (ibsta & ERR) {
		GPIBCleanup(Dev, "Unable to open device");
		return 1;
	}

	ibsic(Dev); // 接口清零并使 GPIB 卡为控者
	ibsre(Dev, 1); // 进入远控
	if (ibsta & ERR) {
		GPIBCleanup(Dev, "Unable to clear device");
		return 1;
	}

	ibcmd(Dev, "@+", 2L); // 发讲地址和听地址
	ibcmd(Dev, "\04", 1L); // 发有选择的器件清 SDC
	ibwrt(Dev, "*IDN?", 5L); // 发送命令 
	ibcmd(Dev, " K", 2L); // 发空格和字母 “K” 使 GPIB 卡为听者，器件为讲者
	if (ibsta & ERR) {
		GPIBCleanup(Dev, "Unable to read data from device");
		return 1;
	}

	ibrd(Dev, ReadBuffer, ARRAYSIZE); //读取返回信息
	ReadBuffer[ibcntl] = '\0';
	printf("Returned string:  %s\n", ReadBuffer);

	ibonl(Dev, 0); //使器件或接口复位或脱线，同时删除 ibfind 产生的 Dev 值
	return 0;
}

void GPIBCleanup(int ud, char* ErrorMsg) {
	printf("Error : %s\nibsta = 0x%x iberr = %d (%s)\n", ErrorMsg, ibsta,
			iberr, ErrorMnemonic[iberr]);
	if (ud != -1) {
		printf("Cleanup: Taking device offline\n");
		ibonl(ud, 0);
	}
}
